import { HttpException, Injectable } from '@nestjs/common';
import * as OSS from 'ali-oss';
import * as dayjs from 'dayjs';
import path from 'path';
const fs = require('fs');

@Injectable()
export class FileService {
  private client: any;

  public constructor() {
    this.client = new OSS({
      accessKeyId: process.env.ALIOSS_ACCESS_KEY_ID,
      accessKeySecret: process.env.ALIOSS_ACCESS_KEY_SECRET,
      region: process.env.ALIOSS_REGFION,
      bucket: process.env.ALIOSS_BUCKET,
    });
  }

  // 上传文件到oss 并返回  图片oss 地址
  public async putOssFile(
    originalname: string,
    localPath: string,
  ): Promise<string> {
    let now = dayjs().valueOf();
    let ossPath = `/uploads/${now}_${originalname}`;
    try {
      let res = await this.client.put(ossPath, localPath);
      // 将文件设置为公共可读
      await this.client.putACL(ossPath, 'public-read');

      // 删除本地文件
      fs.unlinkSync(localPath);

      return res.url;
    } catch (error) {
      throw new HttpException('上传文件失败', 400);
    }
  }
}
